# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name:         utility
# Description:  
# Author:       Administrator
# Date:         2020/2/10
#-------------------------------------------------------------------------------

# 将类似于文件读写及其它工具类方法都在此存放
# 对类中的方法增加装饰器@classmethod,则该方法可以被类直接访问
# 该模块中的方法应该不依赖于具体的应用，也不应该依赖于具体的库
from selenium import webdriver
class Utility:

	# 从某个路径读取文件内容
	@classmethod
	def get_txt(cls,path):
		with open(path,encoding='utf8') as file:
			return file.readlines()

	# 将文本读取的内容进行转化处理,由于测试数据的每一项有具体涵义，所以转化为[(),(),()]
	@classmethod
	def trans_txt_tuple(cls,path):
		li = []
		contents = cls.get_txt(path)
		for content in contents:
			if not content.startswith("#"):
				temp = content.strip().split(',')
				tup = tuple(temp)
				li.append(tup)
		return li

	# 将文本内容转化为json格式[{},{},{}] 放在utility中不太合适，因为它依赖于应用
	@classmethod
	def trans_txt_dict(cls,path):
		li = []
		contents = cls.get_txt(path)
		for content in contents:
			if not content.startswith('#'):
				temp = content.strip().split(',')
				di = {"username":temp[0],"password":temp[1],"verifycode":temp[2],"expect":temp[3]}
				li.append(di)
		return li



	# 读取json文件中的内容
	# json是用于存储和数据传递的格式之一.txt是无格式的，处理起来比较麻烦
	# excel，xml，json（key:value）
	@classmethod
	def get_json(cls,path):
		import json
		with open(path) as file:
			contents = json.load(file)
		return contents

	# 判断页面上的某个元素是否存在
	# 该方法依赖于webdriver库
	@classmethod
	def is_element_present(cls,driver, how, what):

		from selenium.common.exceptions import NoSuchElementException
		try:
			driver.find_element(by=how, value=what)
		except NoSuchElementException as e:
			# 表示没找到
			return False
		return True

	# 向一个文本输入框执行三个固定操作：点击、清理、输入
	# 依赖于webdriver
	@classmethod
	def send_input(cls,ele,value):
		ele.click()
		ele.clear()
		ele.send_keys(value)

	# 传入两个值，判断这两个值是否相同.断言相等
	@classmethod
	def assert_equals(cls,expect,actual):
		if expect == actual:
			return True
		else:
			return False

	# 随机选择下拉框中的一项
	# 依赖于webdriver
	@classmethod
	def select_random(cls,selecter):  # selecter是传递的下拉框元素
		from selenium.webdriver.support.select import Select
		seleter_length = len(Select(selecter).options)
		import random
		random_index = random.randint(0,seleter_length-1)
		Select(selecter).select_by_index(random_index)

	# 去掉某个元素的只读属性（id）
	# 依赖于webdriver
	@classmethod
	def remove_readonly(cls,driver,ele_id):
		driver.execute_script('document.getElementById("%s").readOnly=false'%(ele_id))

	# 打开页面的方法
	# 既依赖于应用，也依赖于webdriver
	@classmethod
	def open_page(cls, driver,path):
		contents = Utility.get_json(path)
		URL = 'http://%s:%s/%s' % (contents['HOSTNAME'], contents['PORT'], contents['AURL'])
		driver.get(URL)

	# 具体的业务功能需要绕过登录，使用cookie
	# 与应用强相关，还依赖于webdriver
	@classmethod
	def miss_login(cls,driver,path):
		cls.open_page(driver,path)
		# 通过字典方式传递cookie信息
		contents = cls.get_json(path)
		driver.add_cookie({'name':'username','value':contents['username']})
		driver.add_cookie({'name':'password','value':contents['password']})
		cls.open_page(driver, path)

	# 获取数据库连接
	# 依赖于配置文件的规则
	@classmethod
	def getConn(cls,path):
		import pymysql
		db_info = cls.get_json(path)
		return pymysql.connect(db_info['HOSTNAME'], db_info['DBUSER'], db_info['DBPASSWORD'], db_info['DBNAME'], charset='utf8')

	# 查询一条记录
	@classmethod
	def query_one(cls, path,sql):
		# 获取数据库连接对象
		conn = cls.getConn(path)
		cursor = conn.cursor()
		cursor.execute(sql)
		result = cursor.fetchone()
		cursor.close()
		conn.close()
		# 返回一维元组
		return result

	# 查询多条记录
	@classmethod
	def query_all(cls,path, sql):
		# 获取数据库连接对象
		conn = cls.getConn(path)
		cursor = conn.cursor()
		cursor.execute(sql)
		result = cursor.fetchall()
		cursor.close()
		conn.close()
		# 返回二维元组
		return result

	# 更新记录
	@classmethod
	def update_data(cls,path, sql):
		flag = False
		try:
			conn = cls.getConn(path)
			cursor = conn.cursor()
			cursor.execute(sql)
			# 将数据真正提交到数据库中
			conn.commit()
			flag = True
		finally:
			cursor.close()
			conn.close()
			# 不管更新操作是否成功，都会返回真或假的结果
			return flag

if __name__ == '__main__':
    # Utility.trans_txt('..\\config\\base.conf')
	# Utility.get_json('..\\config\\base.conf')
	# login_testdata = Utility.trans_txt('..\\testdata\\login_data')
	# print(login_testdata)
	# login_testdata = Utility.trans_txt_dict('..\\testdata\\login_data')
	# print(login_testdata)
    driver = webdriver.Firefox()
    Utility.miss_login(driver,'..\\config\\base.conf')